#include "mainwindow.h"
//#include "ui_mainwindow.h"
#include "rmsqlmanager.h"
#include "../rmutils.h"
#include <QJsonObject>

MainWindow::MainWindow(QObject *parent)
    : QObject(parent)
{
    m_pWebSocketServer = new QWebSocketServer(QStringLiteral("Echo Server"),
                                                QWebSocketServer::NonSecureMode, this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_start_clicked()
{
    if (m_pWebSocketServer->listen(QHostAddress::Any,10004)) {
        connect(m_pWebSocketServer, &QWebSocketServer::newConnection,
                this, &MainWindow::onNewConnection);
        //connect(m_pWebSocketServer, &QWebSocketServer::closed, this, [=]);
        qDebug()<<"websocket start success";
    }
}

void MainWindow::onNewConnection()
{
    QWebSocket *pSocket = m_pWebSocketServer->nextPendingConnection();

    connect(pSocket, &QWebSocket::textMessageReceived, this, &MainWindow::processTextMessage);
    connect(pSocket, &QWebSocket::binaryMessageReceived, this, &MainWindow::processBinaryMessage);
    connect(pSocket, &QWebSocket::disconnected, this, &MainWindow::socketDisconnected);
    m_clients << pSocket;

}

void MainWindow::processTextMessage(QString message)
{
    QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());
    if (m_debug)
        qDebug() << "Message received:" << message;
    if (pClient) {
        QString sendMessage;
        QJsonObject reciveobj=RMUtils::QstringToJson(message);
        QJsonObject sendObj;
        QString messagetype = reciveobj.value("type").toString();
        sendObj.insert("type",messagetype);
        if(messagetype == "Type_Login")
        {
            QString phone = reciveobj.value("phone").toString();
            if(!m_clientIDs.contains(pClient))
                m_clientIDs[pClient]=phone;
            qDebug()<<"m_clientIDs:"<<m_clientIDs;
            QString pwd = reciveobj.value("pwd").toString();
            int loginres = RMSqlManager::gSQLInstance->checkUserCount(phone,pwd);
            switch (loginres) {
            case 0:
                {
                    sendObj.insert("res","success");
                }
                break;
            default:
                break;
            }
            qDebug()<<"return msg:"<<sendObj;
            pClient->sendTextMessage(RMUtils::JsonToQstring(sendObj));
        }
        if(messagetype == "Type_Enterroom")
        {
            QString room = reciveobj.value("room").toString();
            if(!m_rooms[room].contains(pClient))
                m_rooms[room].append(pClient);
            qDebug()<<"m_rooms:"<<m_rooms;
            QJsonObject temobj = sendObj;
            QString phones;
            foreach (QWebSocket* client, m_rooms[room]) {
                phones.append(m_clientIDs[client]);
                phones.append(",");
            }
            phones = phones.left(phones.size()-1);
            temobj.insert("phones",phones);
            qDebug()<<"return msg:"<<temobj;
            foreach (QWebSocket* client, m_rooms[room]) {
                client->sendTextMessage(RMUtils::JsonToQstring(temobj));
            }
        }
        if(messagetype == "Type_Leaveroom")
        {
            QString room = reciveobj.value("room").toString();
            if(m_rooms.contains(room))
            {
                QJsonObject temobj = sendObj;
                temobj.insert("phone",m_clientIDs[pClient]);
                foreach (QWebSocket* client, m_rooms[room]) {
                     client->sendTextMessage(RMUtils::JsonToQstring(temobj));
                }
            }
        }




    }
}

void MainWindow::processBinaryMessage(QByteArray message)
{
    QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());
    if (m_debug)
        qDebug() << "Binary Message received:" << message;
    if (pClient) {
        pClient->sendBinaryMessage(message);
    }
}

void MainWindow::socketDisconnected()
{
    QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());
    if (m_debug)
        qDebug() << "socketDisconnected:" << pClient;
    if (pClient) {



        QMap<QString,QVector<QWebSocket*>>::iterator roomsiterator;
        for (roomsiterator = m_rooms.begin();roomsiterator!=m_rooms.end();roomsiterator++) {
            QVector<QWebSocket*>& tempvalue = roomsiterator.value();
            if(tempvalue.contains(pClient))
            {
                tempvalue.removeOne(pClient);
                foreach(QWebSocket* socket,tempvalue)
                {
                    QJsonObject sendObj;
                    QString messagetype ="Type_Leaveroom";
                    sendObj.insert("type",messagetype);
                    sendObj.insert("phone",m_clientIDs[pClient]);
                    qDebug()<<"return msg:"<<sendObj;

                    socket->sendTextMessage(RMUtils::JsonToQstring(sendObj));
                }
            }
        }

        m_clientIDs.remove(pClient);
        m_clients.removeAll(pClient);
        pClient->deleteLater();
    }
}
